<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

class Pigai extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 批单列表
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_pigai_list(){
        $where = input('post.');
        $user = $this->getUser(2);
        $map = array();
        if(isset($where['title']) && $where['title']){
            $title = $where['title'];
            $map['pigai_numz|pigai_nump|car_num|car_vin'] = ['like',"%$title%"];
        }
//        if(isset($where['pigai_numz']) && $where['pigai_numz']){
//            $map['pigai_numz']=$where['pigai_numz'];
//        }
//        if(isset($where['pigai_nump']) && $where['pigai_nump']){
//            $map['pigai_nump']=$where['pigai_nump'];
//        }
//        if(isset($where['car_num']) && $where['car_num']){
//            $map['car_num']=$where['car_num'];
//        }
//        if(isset($where['car_vin']) && $where['car_vin']){
//            $map['car_vin']=$where['car_vin'];
//        }


        if(isset($where['learned_name']) && $where['learned_name']){
            $map['learned_name']=$where['learned_name'];
        }
        if(isset($where['lururen']) && $where['lururen']){
            $map['lururen']=$where['lururen'];
        }
        if(isset($where['zuzhi']) && $where['zuzhi']){
            $zuzhi = zuzhi($where['zuzhi_id']);
            $map['yw_class'] = ['in',$zuzhi];
        }else {
            if($user['admin_id'] != 1){
                $zuzhi = zuzhi($user['admin']['zuzhi_id']);
                $map['yw_class'] = ['in',$zuzhi];
            }
        }

        if(isset($where['status']) && $where['status']){
            $map['status'] = $where['status'];
        }
        $page = input('post.page',1);
        $limit = input('post.limit',10);
        $field = 'id,batch_state,pigai_numz,pigai_nump,car_num,car_vin,learned_name,pigai_ctime,yw_join_time,pigai_type,status,lururen,yw_class';
        $data = Db::name('list_three')->where($map)->where('deletetime',)->field($field)->page($page,$limit)->order('id desc')->select();
        if($data){
            foreach ($data as &$v){
                $v['zuzhi'] = Db::name('zuzhi')->where(['id' => $v['yw_class']])->value('name');
                $v['pigai_ctime'] = $v['pigai_ctime'] ? date('Y-m-d H:i:s', $v['pigai_ctime']) : '';
                $v['yw_join_time'] = $v['yw_join_time'] ? date('Y-m-d H:i:s', $v['yw_join_time']) : '';
            }
        }
        $count = Db::name('list_three')->where($map)->where('deletetime',)->count();
        $this->success('',['data'=>$data,'count'=>$count]);
    }
    /**
     * 查询批单提交信息是否存在
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function chaxun(){
        $where = input('post.');
        $map = array();
        if(isset($where['car_engine']) && $where['car_engine']){
            $map['car_engine']=$where['car_engine'];
        }
        if(isset($where['tong_number']) && $where['tong_number']){
            $map['tong_number']=$where['tong_number'];
        }
        if(isset($where['car_vin']) && $where['car_vin']){
            $map['car_vin']=$where['car_vin'];
        }
        if(isset($where['car_num']) && $where['car_num']){
            $map['car_num']=$where['car_num'];
        }
        if(!$map) $this->error('至少填写一项');
        $map['status']=5;
        $data = db('list_one')->where($map)->where('deletetime',)->field('kehu_sumdiscount,chexing_ci,feiyong,yw_peo,yw_peo_phone,jiaofei,jiaofei_price,jiaofei_type,type,feiyong_type,jiafei_type,shui_lv1,tcxm,status_type,qianzi_status,chezhu,tk_type,bjt,openid,jq_price,cc_price,user_id,tong_document,give_number,jiaofei_time,urls1,urls2',1)->find();
        if (!$data) {
            $this->error('没找到相关信息');
        }else{
            $info = Db::name('list_three')->where('ids',$data['id'])->where('deletetime',)->whereNotIn('status',[0,4,5])->find();
            if($info) $this->error('存在审核中的批单');
        }
        $id = $data['id'];
        $data['car_register'] = date('Y-m-d',$data['car_register']);
        $data['plan_strattime'] = date('Y-m-d H:i:s', $data['plan_strattime']);
        $data['plan_endtime'] = date('Y-m-d H:i:s', $data['plan_endtime']);
        $data['yw_class'] = db('zuzhi')->where('id',$data['yw_class'])->value('name');
        $data['file'] = db('tong_files')->where('tong_id',$id)->select();
        $this->success('',$data);
    }

    /**
     * 批单详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_pigai_info(){
        $id = input('post.id',0);
        if(!$id) $this->error('参数错误');
        $data = Db::name('list_three')->where('id',$id)->find();
        if(!$data){
            $this->error('数据不存在');
        }
        $data['car_register'] = date('Y-m-d',$data['car_register']);
        $data['plan_strattime'] = date('Y-m-d H:i:s', $data['plan_strattime']);
        $data['plan_endtime']   = date('Y-m-d H:i:s', $data['plan_endtime']);
        $data['yw_class'] = db('zuzhi')->where('id',$data['yw_class'])->value('name');
        $data['file'] = db('tong_files')->where('tong_id',$data['ids'])->select();
        $data['yijian'] = db('yijian')->where('did',$data['ids'])->select();
        $this->success('',$data);
    }

    /**
     * 删除批单
     * @return void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pigai_del(){
        $id = input('post.id',0);
        if(!$id) $this->error('参数错误');
        Db::name('list_three')->where('id',$id)->update(['deletetime' => time()]);
        $this->success('删除成功');
    }

    /**
     * 驳回
     * @return void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public  function pigai_reject(){
        $id = input('post.id',0);
        if(!$id) $this->error('参数错误');
        Db::name('list_three')->where('id',$id)->update(['status'=>4,'pigai_nump'=>null]);
        $this->success('成功');
    }

    /**
     * 撤回
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pigai_withdraw(){
        $id = input('post.id',0);
        if(!$id) $this->error('参数错误');
        $info = Db::name('list_three')->where('id',$id)->find();
        if($info['status'] == 5){
            $this->error('已生成服务单,不可进行操作');
        }else{
            Db::name('list_three')->where('id',$id)->update(['status'=>4]);
            $this->success('成功');
        }
    }

    /**
     * 批改提交
     */
    public function upshens(){
        $param = request()->param();
        $xiudata = $param['data'];
        if(!isset($xiudata['batch_state']) || !$xiudata['batch_state']) $this->error('批单状态不能为空');
        $id = 0;
        if(isset($xiudata['id']) && $xiudata['id']){
            $id = $xiudata['id'];
            unset($xiudata['id']);
        }
        $one_id = $xiudata['ids'];
        $xiudata['pigai_type'] = 1;
        $xiudata['status']=2;
        $xiudata['car_register'] = strtotime($xiudata['car_register']);
        $xiudata['plan_strattime'] = strtotime($xiudata['plan_strattime']);
        $xiudata['plan_endtime'] = strtotime($xiudata['plan_endtime']);
        //1、获取本商户的最新进货单号
        $xiudata['pigai_numz'] = zancun("list_three", "pigai_numz", "P");
        $xiudata['pigai_ctime'] = time();
        $urls = $param['img'];
        // 启动事务
        Db::startTrans();
        try {
            $xiudata['pigai_type']=1;
            $xiudata['status']=2;
            header("Content-Type: text/html; charset=utf-8");
            // 修改日志
            $changes = recordChanges($one_id, $xiudata);
            db('change_log')->insert(['oneid'=>$one_id, 'content'=>$changes]);
            if (!$id){
                $user = $this->getUser(2);
                $xiudata['lururen'] = $user['admin']['username'];
                $xiudata['lururen_id'] = $user['admin']['id'];
                $uplistone = db('list_three')->insertGetId($xiudata);
            } else {
                unset($xiudata['ids']);
                $uplistone = db('list_three')->where('id', $id)->update($xiudata);
            }
            //保存图片
            saveOneFile($one_id, $urls);
            if ($uplistone) {
                // 提交事务
                Db::commit();
            } else {
                Db::rollback();
                $this->error('提交失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('报错了'.$e->getMessage());
        }
        $this->success('保存成功');
    }
    /**
     * 导入批文
     * @return void
     */
    public function pigai_drpiwen(){
        $param = request()->param();
        $xiudata = $param['data'];
        $xiudata['pigai_type'] = 1;
        $xiudata['status']=2;
        $xiudata['car_register'] = strtotime($xiudata['car_register']);
        $xiudata['plan_strattime'] = strtotime($xiudata['plan_strattime']);
        $xiudata['plan_endtime'] = strtotime($xiudata['plan_endtime']);
        $xiudata['pigai_ctime'] = time();
        $one_id = $xiudata['ids'];
        $xiudata['pigai_type']=1;
        $xiudata['status']=2;
        $changes = recordChanges($one_id, $xiudata);
        $this->success('',$changes);
    }


    /**
     * 退回修改方法
     * status 2二级审核   6市级审核  3财务审核  4待修改
     * type 1财务退回
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tuihui()
    {
        $param = request()->param();
        $id                = $param['id'];
        $status = $param['status'];
        $type = $param['type'] ?? 0;
        $data['shen_time'] = time();
        $data['shen_peo']  = $param['shenhe_peo'];
        $user = $this->getUser(2);
        $data['user_id'] = $user['admin']['id'];

        $three = Db::name('list_three')->where('id', $id)->where(['status' => $status])->field('id,batch_state,ids')->find();
        if (!$three) {
            return json(['code' => -1, 'msg' => '系统错误']);
        }
        $data['did']     = $three['ids'];
        if ($param['shenhe_yijian'] == '') {
            $this->error('请填写审核意见');
        } else {
            Db::startTrans();
            try {
                $data['shen_yijian'] = $param['shenhe_yijian'];
                $res                 = Db::name('yijian')->insert($data);
                if($status == 2 && $type == 0){//二级审核退回
                    $dataa['status']     = 4;
                }elseif($status == 6 && $type == 0){//市级审核退回上一步
                    $dataa['status']     = 2;
                }elseif($status == 3 && $type == 0){//财务审核退回上一步
                    $dataa['status']     = 6;
                }elseif($status == 3 && $type == 1){//财务审核退回修改
                    $dataa['status']     = 4;
                }elseif($status == 6 && $type == 1){//市级审核退回修改
                    $dataa['status']     = 4;
                }else{
                    $this->error('参数错误');
                }
                $ress                = Db::name('list_three')->where('id', $id)->update($dataa);
                if ($ress) {
                    Db::commit();
                } else {
                    Db::rollback();
                    $this->error('失败');
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->success('成功');
    }

    /**
     * 审核方法
     * status 2二级审核   6市级审核  3财务审核  4待修改
     * type 1财务退回
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shenhe()
    {
        $param = request()->param();
        $id = $param['id'];
        $status = $param['status'];
        $data['shen_time'] = time();
        $data['shen_peo']  = $param['shenhe_peo'];
        $user = $this->getUser(2);
        $data['user_id'] = $user['admin']['id'];
        $three = Db::name('list_three')->where('id', $id)->where(['status' => $status])->field('id,batch_state,ids')->find();
        if (!$three) {
            return json(['code' => -1, 'msg' => '系统错误']);
        }
        $data['did'] = $three['ids'];
        $batch_state = $three['batch_state']; //1-退单 2-改单（初审） 3-增单（初审、财务）
        // 启动事务
        Db::startTrans();
        try {
            if($status == 2){
                $data['shen_yijian'] = $param['shenhe_yijian'] ? $param['shenhe_yijian'] : "二审(批单)通过";
                $dataa['status'] = 6; // 先进入市级审核
                if ($batch_state == '2') {
                    //直接进入财务审核
                    $dataa['status'] = 5;
                }
                $dataa['pigai_nump'] = zancun("list_three", "pigai_nump", "PTP");
                $dataa['shenhe_peo'] = $param['shenhe_peo'];
            }elseif($status == 6){
                $data['shen_yijian'] = $param['shenhe_yijian'] ? $param['shenhe_yijian'] : "市级财务(批单)通过";
                $dataa['shenhe_peo']   = $param['shenhe_peo'];
                $dataa['main_netrate'] = $param['row']['main_netrate'];
                $dataa['main_netcost'] = $param['row']['main_netcost'];
                $dataa['main_tongchoufee_heji']     = $param['row']['main_tongchoufee_heji'];
                $dataa['main_xiaoguan_bili']        = $param['row']['main_xiaoguan_bili'];
                $dataa['main_xiaoguan']             = $param['row']['main_xiaoguan'];
                $dataa['main_yunying_bili']         = $param['row']['main_yunying_bili'];
                $dataa['main_yunying']              = $param['row']['main_yunying'];
                $dataa['main_tongchoujingfee_heji'] = $param['row']['main_tongchoujingfee_heji'];
                if (!empty($param['row']['dong_fee']) || strlen($param['row']['dong_fee']) != 0) {
                    $dataa['dong_fee'] = $param['row']['dong_fee'];
                }
                $dataa['status']       = 3;
                $dataa['yw_shenhe_time'] = time();
                $dataa['yw_finance_peo'] = $param['shenhe_peo'];
            }elseif($status == 3){
                $data['shen_yijian'] = $param['shenhe_yijian'] ? $param['shenhe_yijian'] : '财务审核(批单)通过';
                $dataa['status']         = 5;
                $dataa['yw_shenhe_time'] = time();
                $dataa['yw_finance_peo'] = $param['shenhe_peo'];
            }
            $res             = Db::name('yijian')->insert($data);
            $ress = Db::name('list_three')->where('id', $id)->update($dataa);
            if($status == 3 || ($status == 2 && $batch_state == 2)){
                genghuan_one($id);
            }
            // 提交事务
            Db::commit();
            return json(['code' => 1, 'msg' => '请求成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 0, 'msg' => '失败' . $e->getMessage() . '，异常行：' . $e->getLine() . '，异常路径：' . $e->getfile()]);
        }
    }

    public function callDeepSeekAPI() {
        $apiKey = 'sk-66f0eb519f994abc9bce60215be4670b';
        $url = 'https://api.deepseek.com/chat/completions';
        $message = '晚上吃什么';
        $data = [
            "model" => "deepseek-chat",
            'messages' => [
                ["role" => "user", "content" => $message]
            ],
            'stream'=>false
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        ]);

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            curl_close($ch);
            return json_encode(['error' => $error_msg]);
        }
        curl_close($ch);

        $response = json_decode($response, true);
        print_R($response);exit;
        return json_encode(['content'=>$response['choices'][0]['message']['content']]);
    }

}